package com.yuqih.common.service.impl;

import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.GenericTypeResolver;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.yuqih.common.config.IFrameworkConfigInitializing;
import com.yuqih.common.dto.Page;
import com.yuqih.common.dto.PageMetadata;
import com.yuqih.common.service.IBaseService;
import com.yuqih.common.service.ICommonService;

public abstract class BaseService<T, K, C> implements IBaseService<T, K, C> {

	private final Class<T> type;
	private final Class<C> conditionType;

	@Autowired
	protected ICommonService commonService;
	
	@Autowired
	private IFrameworkConfigInitializing frameworkConfigInitializing;

	@SuppressWarnings("unchecked")
	public BaseService() {
		super();
		Class<?>[] types = GenericTypeResolver.resolveTypeArguments(getClass(), IBaseService.class);
		Assert.notNull(types, "无法解析泛型");
		this.type = (Class<T>) types[0];
		this.conditionType = (Class<C>) types[2];
	}

	protected BaseService(Class<T> type, Class<C> conditionType) {
		super();
		this.type = type;
		this.conditionType = conditionType;
	}
	
	@PostConstruct
	public void init() {
		frameworkConfigInitializing.registerBaseService(type, this, conditionType);
	}

	@Transactional
	@Override
	public void save(T model) {
		commonService.save(type, model);

	}
	
	@Transactional
	@Override
	public void save(List<T> models) {
		commonService.save(type, models);
	}

	@Transactional
	@Override
	public void modify(T model) {
		commonService.modify(type, model);

	}
	
	@Transactional
	@Override
	public void modify(List<T> models) {
		commonService.modify(type, models);

	}

	@Transactional
	@Override
	public void remove(K id) {
		commonService.remove(type, id);
	}
	
	@Deprecated
	@Transactional
	@Override
	public void remove(K[] ids){
		for (K id : ids) {
			remove(id);
		}
	}
	
	@Transactional
	@Override
	public void remove(List<K> ids){
		commonService.remove(type, ids);
	}

	@Transactional
	@Override
	public T findById(K id) {
		return commonService.findById(type, id);
	}

	@Transactional
	@Override
	public List<T> list(C condition) {
		return commonService.list(type, condition);
	}

	@Transactional
	@Override
	public Page<T> page(C condition, PageMetadata pageMetadata) {
		return commonService.page(type, condition, pageMetadata);
	}

}
